
#include <iostream>
#include <stdint.h>

#include "core/client/Receiver.h"
#include "core/common/Packet.h"
#include "network/Socket.h"

Receiver::Receiver(Socket* socket,bool* isPilot)
    : AbstractThread(), pSocket_(socket)
{
    isPilot_ = isPilot;
}

Receiver::~Receiver()
{
}

void Receiver::run()
{
    uint8_t buffer[Protocol::maxPacketSize] = { 0 };
    int left = 0;
    int right = 0;

    do
    {
        // Décalage vers la gauche du buffer
        if(left > 0)
            for(int i = 0; i < right - left; ++i)
                buffer[i] = buffer[i + left];
        right -= left;
        left = 0;

        // Ajouter au buffer tant que nécessaire
        int minSize = Protocol::minPacketSize;
        do
        {
            int r = pSocket_->read(&(buffer[right]), Protocol::maxPacketSize - right);
            right += r;

            // Gestion des erreurs
            if(r < 0)
            {
                std::cerr << "> Could not read from " << pSocket_->interface() << " : " << std::endl;
                std::cerr << "> " << pSocket_->errorString() << std::endl;

                left = 0;
                right = 0;
            }
            // Gestion de la déconnexion
            else if(r == 0)
            {
                std::cout << "> " << pSocket_->interface() << " had disconnected" << std::endl;
                pSocket_->close();
            }

        } while(right < minSize);

        // Traitement
        int type = ((BasePacket*)&buffer)->type;
        switch(type)
        {
        case Protocol::control:
            std::cout << "> Now in control !" << std::endl;
            left += sizeof(BasePacket);
            *isPilot_ = true;
            break;

        case Protocol::update:
            UpdatePacket* updatePacket = (UpdatePacket*)&buffer;
            std::cout << "> Update : " << updatePacket->x << ", " << updatePacket->y << std::endl;
            left += sizeof(UpdatePacket);
            break;
        }

    } while(pSocket_->isOpen());  // On vérifie que le serveur ne s'est pas déconnecté
}
